import Vue from 'vue'
import VueRouter from 'vue-router'
import Dashboard from '../views/Dashboard.vue'
import Login from '../views/Login.vue'
import AuthLayout from '../components/AuthLayout.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: AuthLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: Dashboard
      },

      {
        path: '/questions',
        name: 'Questions',
        component: () => import('../views/Questions.vue')
      },
      {
        path: '/students',
        name: 'Students',
        component: () => import('../views/Students.vue')
      },
      {
        path: '/admins',
        name: 'Admins',
        component: () => import('../views/Admins.vue')
      },
      {
        path: '/question-analytics',
        name: 'QuestionAnalytics',
        component: () => import('../views/QuestionAnalytics.vue')
      },
      {
        path: '/user-analytics',
        name: 'UserAnalytics',
        component: () => import('../views/UserAnalytics.vue')
      },
      {
        path: '/settings',
        name: 'Settings',
        component: () => import('../views/AdminSettings.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('token');
  
  // 如果路由需要认证
  if (to.meta.requiresAuth) {
    // 如果未登录，重定向到登录页
    if (!isLoggedIn) {
      next('/login');
    } else {
      next();
    }
  } else {
    // 如果已登录且访问登录页，重定向到首页
    if (to.path === '/login' && isLoggedIn) {
      next('/');
    } else {
      next();
    }
  }
})

export default router
